package ex2;

import common.Utils;
import common.exceptions.ParseException;
import ex2.grammars.GrammarFactory;
import ex2.grammars.GrammarType;
import ex2.grammars.IGrammar;
import fun.parser.Tree;
import ic.ast.Node;
import ic.ast.PrettyPrint;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Roi
 * Date: 09/11/13
 */
public class Ex2 {

    public static void run(String[] args) {

        if (args.length == 0)
            return;

        List<Token> tokens;
        ITokenizer tokenizer = new JflexTokenizer();

        try {
            tokens = tokenizer.tokenize(Utils.fileToString(args[0]));
            process(tokens, GrammarFactory.createGrammar(GrammarType.GRAMMAR_TYPE_PROGRAM));

            if (args.length == 2) {
                tokens = tokenizer.tokenize(Utils.fileToString(args[1]));
                process(tokens, GrammarFactory.createGrammar(GrammarType.GRAMMAR_TYPE_LIBRARY));
            }
        }
        catch(ParseException e) {
            System.out.println(e.getMessage());
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void process(List<Token> tokens, IGrammar grammar) throws Exception {
        Tree parseTree = grammar.constructParseTree(tokens);
        Node ast = grammar.constructAst(parseTree);
        System.out.println(ast.accept(new PrettyPrint()));
    }
}
